import { format, parseISO } from 'date-fns'
import iconFile from '@assets/addr.png'
import watermark from 'watermarkjs'

// 组装地址数据
export const transformOptions = (options) => {
    return options.map((item) => ({
        label: item.option,
        value: item.option,
        children: item.children?.length ? transformOptions(item.children) : undefined
    }))
}

export function parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    let _time
    if (typeof time === 'object') {
        date = time
    } else {
        _time = time
        if (typeof time === 'string') {
            if (/^[0-9]+$/.test(time)) {
                // support "1548221490638"
                _time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                _time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if (typeof time === 'number' && time.toString().length === 10) {
            _time = time * 1000
        }
        date = new Date(_time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

export function random_string(len = 8, chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678') {
    const maxPos = chars.length
    let pwd = ''
    for (let i = 0; i < len; i++) pwd += chars.charAt(Math.floor(Math.random() * maxPos))

    return pwd
}

export function getSelected(data) {
    const selected = {}

    // 遍历每个分类
    for (const category in data) {
        selected[category] = []

        // 遍历每个分类中的项目
        for (const item in data[category]) {
            if (data[category][item]) {
                selected[category].push(item)
            }
        }
    }

    return selected
}

// 格式化 "YYYY-MM-DD HH:mm:ss" 为 "YYYY-MM-DDTHH:mm"
export function formatDateTimeForInput(time = getCurrentBeijingTime()) {
    const date = parseISO(time)
    return format(date, "yyyy-MM-dd'T'HH:mm")
}

// 解析 "YYYY-MM-DDTHH:mm" 回 "YYYY-MM-DD HH:mm:ss"
export function parseInputDateTime(time = getCurrentBeijingTime()) {
    const date = parseISO(time)
    return format(date, 'yyyy-MM-dd HH:mm:ss')
}

// 获取当前北京时间
export function getCurrentBeijingTime() {
    return format(new Date(), 'yyyy-MM-dd HH:mm:ss', { timeZone: 'Asia/Shanghai' })
}

// 处理线上图片或本地文件
export const handleImage = (srcOrFile) => {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'Anonymous' // 设置跨域（对于在线图片）

        img.onload = () => {
            resolve(img)
            // 如果 src 是由 URL.createObjectURL 创建，需要在加载后释放
            if (srcOrFile instanceof File) {
                URL.revokeObjectURL(img.src)
            }
        }
        img.onerror = reject

        // 判断 srcOrFile 是在线图片地址还是本地文件对象
        if (srcOrFile instanceof File) {
            img.src = URL.createObjectURL(srcOrFile) // 本地文件转换为URL
        } else {
            img.src = srcOrFile // 直接使用在线图片地址
        }
    })
}

export const customTextMark = (img, icon, watermarkText) => {
    watermarkText = watermarkText || '14:28/2024-08-25 星期天/成都市·新都区'
    const ctx = img.getContext('2d')
    const width = img.width
    const height = img.height
    const textArr = watermarkText.split('/')
    console.log(watermarkText, textArr)

    // 绘制文本
    ctx.font = `${width / 10}px 黑体`
    ctx.fillStyle = 'white'
    ctx.fillText(textArr[0], (width - ctx.measureText(textArr[0]).width) / 2, height - 160)
    ctx.font = `${width / 48}px 黑体`
    ctx.fillText(textArr[1], (width - ctx.measureText(textArr[1]).width * 2) / 2 - 40, height - 70)
    ctx.fillText(textArr[2], width / 2 + 40, height - 70)
    // 绘制图标
    ctx.drawImage(icon, width / 2 - 10, height - 110, 50, 50) // 调整图标位置和大小

    return img
}

export const getWatermark = (file, watermarkText) => {
    return new Promise((resolve) => {
        handleImage(file).then((image) => {
            const iconPromise = handleImage(iconFile) // 加载图标
            iconPromise.then((icon) => {
                // 创建带水印的图片
                watermark([image])
                    .image((img) => customTextMark(img, icon, watermarkText))
                    .then((img) => {
                        resolve(img.src)
                    })
            })
        })
    })
}
